package com.siwei.mes.sync.erp.service.impl;

import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.config.CompanyConfigInterceptor;
import com.siwei.mes.entity.erp.Itemorder;
import com.siwei.mes.entity.experiment.*;
import com.siwei.mes.entity.materials.Materials;
import com.siwei.mes.entity.system.CompanyConfig;
import com.siwei.mes.enums.MaterialsEnum;
import com.siwei.mes.mapper.experiment.ExperimentItemorderMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.experiment.ExperimentTaskMapper;
import com.siwei.mes.service.materials.MaterialsService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 生成混凝土委托抽象类
 *
 * @Description: 生成混凝土抽象
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/11 17:55
 */
@Service
public class GenAbstractService {
    private static final Logger log = LoggerFactory.getLogger("erp");
    @Resource
    private MaterialsService materialsService;
    @Resource
    private ExperimentItemorderMapper experimentItemorderMapper;
    @Resource
    private ExperimentTaskMapper experimentTaskMapper;
    @Resource
    private ExperimentMapper experimentMapper;

    /**
     * 组装物料相关信息
     *
     * @param tpz        砼品种
     * @param experiment 试验委托信息
     */
    public void payloadMaterialsInfo(String tpz, Experiment experiment) {
        log.info("开始组装物料相关信息，砼品种：【{}】", tpz);
        /**这里最后判断pk_materials表中是否有基础信息  如果没有需要新增*/
        Materials materials = materialsService.checkIsExist(MaterialsEnum.CONCRETE.getCode(), MaterialsEnum.CONCRETE.getName(), tpz);
        if (materials.getSpecId() != null) {
            experiment.setSpecId(materials.getSpecId());
        }
        /**2024-08-24 16:28:23  混凝土这里 只显示传过来的tpz*/
        experiment.setSampleLevel(tpz);
        experiment.setMaterialsId(String.valueOf(materials.getId()));
        experiment.setMaterialsName(NullUtils.ifNull(materials.getMaterialsConfigName()));
        experiment.setMaterialsSpecs(NullUtils.ifNull(materials.getMaterialsConfigSpec()));

        experiment.setMatterName(materials.getMaterialName());
        experiment.setMatterSpecs(materials.getMaterialSpecs());

        /**如果简称没有值 就赋值全称*/
        String abbreviation = materials.getMaterialAbbreviation();
        experiment.setMatterAbbreviation(StringUtils.isBlank(abbreviation) ? materials.getMaterialName() : abbreviation);
        experiment.setMaterialAbbreviation(StringUtils.isBlank(abbreviation) ? materials.getMaterialName() : abbreviation);
        /**备案证号赋值*/
        CompanyConfig companyConfig = CompanyConfigInterceptor.getCompanyConfig(1);
        experiment.setCertificateNo(companyConfig.getCompanyRecord());
        experiment.setMoldingTime(experiment.getEntrustTime());
    }


    /**
     * 生成对应抽检信息
     *
     * @param sampleTestProject 抽检试验项目信息
     * @param experiment        试验台账信息
     * @param lq                龄期  这个只有混凝土抗压强度-28d的才会修改
     * @return
     */
    public ExperimentSampleSmoke getExperimentSampleSmoke(ExperimentSampleTestProject sampleTestProject, Experiment experiment, String lq) {
        log.info("开始生成对应抽检信息，试验项目：【{}】", sampleTestProject.getTestCode());
        ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke();
        sampleSmoke.setId(null);
        sampleSmoke.erpInit(true);
        sampleSmoke.setExperimentId(experiment.getId());
        sampleSmoke.setSampleTime(new Date());
        sampleSmoke.setSampleTestProjectCode(sampleTestProject.getItemCode());
        sampleSmoke.setSampleTestProjectName(sampleTestProject.getItemName());
        /**这个只有混凝土抗压强度-28d的才会修改*/
        if (sampleTestProject.getItemCode().equals("KYQD-28D") && StringUtils.isNotBlank(lq)) {
            try {
                sampleSmoke.setFreqNumber(Integer.valueOf(lq));
            } catch (Exception e) {
                sampleSmoke.setFreqNumber(sampleTestProject.getFreqNumber());
            }
        } else {
            sampleSmoke.setFreqNumber(sampleTestProject.getFreqNumber());
        }
        sampleSmoke.setFreqUnit(sampleTestProject.getFreqUnit());
        sampleSmoke.setIsTestBlock(1);// 是否是试块 1-是 0-不是
        sampleSmoke.setTestProjectCode(sampleTestProject.getTestCode());
        sampleSmoke.setTestProjectName(sampleTestProject.getTestName());
        sampleSmoke.setSampleUse(sampleTestProject.getTestName());
        sampleSmoke.setSamplePersonName(experiment.getEntrustPersonName());
        sampleSmoke.setDisposerPersonName(experiment.getEntrustPersonName());
        return sampleSmoke;
    }

    /**
     * 插入试验台账对应小票数据和试验台账对应ERP任务单记录
     *
     * @param experimentId 试验台账ID
     * @param itemorderId  小票ID
     * @param taskId       任务单ID
     */
    public void insertExperimentRelatedRecords(Long experimentId, Integer itemorderId, Integer taskId) {
        log.info("开始插入试验台账对应小票数据和试验台账对应ERP任务单记录，试验台账ID：【{}】，小票ID：【{}】，任务单ID：【{}】", experimentId, itemorderId, taskId);
        if (experimentId == null) {
            return;
        }
        if (itemorderId != null) {
            ExperimentItemorder experimentItemorder = new ExperimentItemorder().setExperimentId(experimentId).setItemorderId(itemorderId);
            if (experimentItemorderMapper.selectOne(experimentItemorder) == null) {
                experimentItemorderMapper.insertSelective(experimentItemorder);
            }
        }
        if (taskId != null) {
            ExperimentTask experimentTask = new ExperimentTask().setExperimentId(experimentId).setTaskId(taskId);
            if (experimentTaskMapper.selectOne(experimentTask) == null) {
                experimentTask.setCreateTime(new Date());
                experimentTask.setReadTime(null);
                experimentTaskMapper.insertSelective(experimentTask);
                /**这里新增任务单的关联关系 给对应试验委托的isNewTask改为1*/
                log.info(this.getClass().getName() + "新增任务单给对应isNewTask修改为1");
                experimentMapper.updateIsNewTask(experimentId, 1);
            }
        }

    }

    /**
     * 修改试验台账的代表数量
     *
     * @param experimentId 试验台账ID
     */
    public void updateExperimentBehalfNumber(Long experimentId) {
        log.info("开始修改试验台账的代表数量，试验台账ID：【{}】", experimentId);
        List<Itemorder> itemorderList = experimentItemorderMapper.selectByExperimentId(experimentId);
        double behalfNumber = itemorderList.stream().map(Itemorder::getScquantity).reduce((float) 0, Float::sum);
        Experiment updateInfo = new Experiment();
        updateInfo.setId(experimentId);
        updateInfo.setBehalfNumber(behalfNumber);
        updateInfo.erpInit(false);
        experimentMapper.updateByPrimaryKeySelective(updateInfo);
    }

    /**
     * 修改试验台账的代表数量
     *
     * @param experimentId 试验台账ID
     * @param behalfNumber 代表数量
     */
    public void updateExperimentBehalfNumberByXnbg(Long experimentId, Double behalfNumber) {
        log.info("开始修改试验台账的代表数量-性能报告，试验台账ID：【{}】，是否是性能报告：【{}】", experimentId);
        Experiment updateInfo = new Experiment();
        updateInfo.setId(experimentId);
        updateInfo.setBehalfNumber(behalfNumber);
        updateInfo.erpInit(false);
        updateInfo.setIsXnbg(1);
        experimentMapper.updateByPrimaryKeySelective(updateInfo);
    }

    /**
     * 处理异常并回滚事务
     *
     * @param message 异常信息
     * @param e       异常对象
     */
    public void handleException(String message, Exception e) {
        log.error("{}，错误原因：【{}】", message, e.getMessage(), e);
        //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }

}
